// service/pages/recharge/recharge.js
Page({
  data: {
    currentAmount: '300.00', // 当前选中的充值金额
    customAmount: '', // 自定义金额输入
    selectedCard: '摄图银行存蓄卡(5537)', // 选中的银行卡
    showCustomInput: false, // 是否显示自定义输入框
    billId: '', // 账单ID
    billName: '', // 账单名称,
    oweAmount:'',
    rechargeOptions: [
      { amount: '500',  gradient: 'gradient-1' },
      { amount: '800',  gradient: 'gradient-2' },
      { amount: '1000',  gradient: 'gradient-3' },
      { amount: '2000',  gradient: 'gradient-4' },
      { amount: '5000',  gradient: 'gradient-5' },
      { amount: '自定义', gradient: 'gradient-6' }
    ]
  },

  onLoad(options) {
    console.log("当前账单id",options.billId);
    // 如果有传递的账单信息，设置为当前金额
    if (options.billId && options.amount) {
      this.setData({ 
        billId: options.billId,
        billName: decodeURIComponent(options.billName || ''),
        currentAmount: parseFloat(options.amount).toFixed(2),
        oweAmount:options.amount
      });
    } else if (options.amount) {
      // 普通充值，设置金额
      this.setData({ currentAmount: options.amount });
    }
  },

  // 选择充值金额
  selectAmount(e) {
    const index = e.currentTarget.dataset.index;
    const option = this.data.rechargeOptions[index];
    
    if (option.amount === '自定义') {
      this.setData({ 
        showCustomInput: true,
        customAmount: ''
      });
    } else {
      this.setData({ 
        currentAmount: option.amount + '.00',
        showCustomInput: false
      });
    }
  },

  // 自定义金额输入
  onCustomInput(e) {
    let value = e.detail.value;
    // 限制只能输入数字和小数点
    value = value.replace(/[^\d.]/g, '');
    // 限制小数点后两位
    if (value.includes('.')) {
      const parts = value.split('.');
      if (parts[1].length > 2) {
        value = parts[0] + '.' + parts[1].substring(0, 2);
      }
    }
    // 限制最大金额为10000
    if (parseFloat(value) > 10000) {
      value = '10000';
    }
    
    this.setData({ 
      customAmount: value,
      currentAmount: value ? value + '.00' : '0.00'
    });
  },

  // 确认自定义金额
  confirmCustomAmount() {
    if (!this.data.customAmount || parseFloat(this.data.customAmount) <= 0) {
      wx.showToast({
        title: '请输入有效金额',
        icon: 'none'
      });
      return;
    }
    
    if (parseFloat(this.data.customAmount) > 10000) {
      wx.showToast({
        title: '单笔充值金额不能超过1万元',
        icon: 'none'
      });
      return;
    }
    
    this.setData({ 
      showCustomInput: false,
      currentAmount: this.data.customAmount + '.00'
    });
  },

  // 取消自定义输入
  cancelCustomInput() {
    this.setData({ 
      showCustomInput: false,
      customAmount: ''
    });
  },

  // 更换银行卡
  changeBankCard() {
    wx.showActionSheet({
      itemList: ['摄图银行存蓄卡(5537)', '工商银行储蓄卡(1234)', '建设银行信用卡(5678)'],
      success: (res) => {
        const cards = ['摄图银行存蓄卡(5537)', '工商银行储蓄卡(1234)', '建设银行信用卡(5678)'];
        this.setData({ selectedCard: cards[res.tapIndex] });
      }
    });
  },

  // 确认充值
  confirmRecharge() {


    const amount = parseFloat(this.data.currentAmount);
    console.log("amount,",amount);
    console.log(this.data.oweAmount);
    console.log("this.data.billId",this.data.billId);
    if (amount <= 0) {
      wx.showToast({
        title: '请选择充值金额',
        icon: 'none'
      });
      return;
    }

    if (amount > 10000) {
      wx.showToast({
        title: '单笔充值金额不能超过1万元',
        icon: 'none'
      });
      return;
    }
    if (this.data.billId) {
    const params = {
      amount: amount,
      type: 'billPayment',
      card: encodeURIComponent(this.data.selectedCard),
      billId: this.data.billId,
      billName: encodeURIComponent(this.data.billName),
      oweAmount: this.data.oweAmount,
    };
    wx.navigateTo({
      url: `/service/pages/paymentPage/paymentPage?${Object.keys(params).map(key => `${key}=${key === 'amount' ? amount : params[key]}`).join('&')}`,
    })
  }
  },

  // 调用微信支付
  callWechatPay(amount) {
    wx.showLoading({ title: '正在发起支付...' });
    
    // 获取用户token
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.hideLoading();
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    // 获取用户ID
    const app = getApp();
    const residentId = app.globalData.residentId || wx.getStorageSync('residentId');
    if (!residentId) {
      wx.hideLoading();
      wx.showToast({
        title: '用户信息异常',
        icon: 'none'
      });
      return;
    }

    // 检查是否在开发环境，如果是则使用模拟支付
    if (app.globalData.baseUrl && app.globalData.baseUrl.includes('localhost')) {
      console.log('开发环境，使用模拟支付');
      this.simulatePayment(amount);
      return;
    }

    // 构建支付请求参数
    const payData = {
      amount: amount,
      residentId: residentId,
      billId: this.data.billId || '',
      billName: this.data.billName || '',
      paymentType: 'recharge'
    };

    // 调用后端支付接口获取支付参数
    wx.request({
      url: `${app.globalData.baseUrl}/payment/createOrder`,
      method: 'POST',
      data: payData,
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.data && res.data.code === 200) {
          // 获取微信支付参数
          const payParams = res.data.data;
          
          // 调用微信支付
          wx.requestPayment({
            timeStamp: payParams.timeStamp,
            nonceStr: payParams.nonceStr,
            package: payParams.package,
            signType: payParams.signType,
            paySign: payParams.paySign,
            success: (payRes) => {
              console.log('支付成功:', payRes);
              this.handlePaymentSuccess(amount);
            },
            fail: (payErr) => {
              console.error('支付失败:', payErr);
              if (payErr.errMsg.includes('cancel')) {
                wx.showToast({
                  title: '支付已取消',
                  icon: 'none'
                });
              } else {
                wx.showToast({
                  title: '支付失败',
                  icon: 'none'
                });
              }
            }
          });
        } else {
          wx.showToast({
            title: res.data.msg || '创建支付订单失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('请求支付接口失败:', err);
        
        // 如果是404错误，提示接口未实现
        if (err.statusCode === 404) {
          wx.showToast({
            title: '支付接口未实现，请联系开发人员',
            icon: 'none',
            duration: 3000
          });
        } else {
          wx.showToast({
            title: '网络请求失败',
            icon: 'none'
          });
        }
      }
    });
  },

  // 模拟支付（开发环境使用）
  simulatePayment(amount) {
    wx.hideLoading();
    
    wx.showModal({
      title: '模拟支付',
      content: `模拟支付金额：¥${amount}\n\n点击确定模拟支付成功`,
      confirmText: '支付成功',
      cancelText: '支付失败',
      success: (res) => {
        if (res.confirm) {
          // 模拟支付成功
          wx.showToast({
            title: '模拟支付成功',
            icon: 'success'
          });
          
          // 延迟处理支付成功逻辑
          setTimeout(() => {
            this.handlePaymentSuccess(amount);
          }, 1000);
        } else {
          // 模拟支付失败
          wx.showToast({
            title: '模拟支付失败',
            icon: 'none'
          });
        }
      }
    });
  },

  // 处理支付成功
  handlePaymentSuccess(amount) {
    wx.showLoading({ title: '处理中...' });
    
    // 如果有账单ID，调用接口修改账单状态
    if (this.data.billId) {
      this.updateBillStatus();
    }
    
    // 调用接口修改住户可用金额
    this.updateResidentBalance(amount);
  },

  // 调用接口修改账单状态
  updateBillStatus() {
    const token = wx.getStorageSync('token');
    const app = getApp();
    const residentId = app.globalData.residentId || wx.getStorageSync('residentId');
    
    if (!token || !residentId) {
      console.error('缺少必要参数');
      return;
    }

    const requestData = {
      billId: this.data.billId,
      status: 0, // 0表示已缴费
      residentId: residentId.toString(),
      updateTime: this.formatDate(new Date())
    };

    wx.request({
      url: `${app.globalData.baseUrl}/bilManagement/bilManagement`,
      method: 'POST',
      data: requestData,
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        console.log('账单状态更新成功:', res.data);
      },
      fail: (err) => {
        console.error('账单状态更新失败:', err);
      }
    });
  },

  // 调用接口修改住户可用金额
  updateResidentBalance(amount) {
    const token = wx.getStorageSync('token');
    const app = getApp();
    const residentId = app.globalData.residentId || wx.getStorageSync('residentId');
    
    if (!token || !residentId) {
      console.error('缺少必要参数');
      return;
    }

    const requestData = {
      residentId: residentId.toString(),
      amount: amount,
      type: 'recharge',
      updateTime: this.formatDate(new Date())
    };

    wx.request({
      url: `${app.globalData.baseUrl}/resident/updateBalance`,
      method: 'POST',
      data: requestData,
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        wx.hideLoading();
        console.log('住户余额更新成功:', res.data);
        
        if (res.data && res.data.code === 200) {
          wx.showToast({
            title: '充值成功',
            icon: 'success'
          });
          
          // 延迟跳转到生活缴费页面
          setTimeout(() => {
            wx.redirectTo({
              url: '/service/pages/payment/payment'
            });
          }, 1500);
        } else {
          wx.showToast({
            title: res.data.msg || '余额更新失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('住户余额更新失败:', err);
        wx.showToast({
          title: '余额更新失败',
          icon: 'none'
        });
      }
    });
  },

  // 格式化日期
  formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  },

  // 返回上一页
  goBack() {
    wx.navigateBack();
  }
});